//
//  ZYPNGDecoder.m
//  ZYWebImage
//
//  Created by wangzhipan on 2025/3/6.
//

#import "ZYPNGDecoder.h"
#import "UIImage+Extra.h"
#import "IZYImageCacheProtocol.h"
@interface ZYPNGDecoder() {
    NSData *_data;
}
@end

@implementation ZYPNGDecoder
- (instancetype)initWithData:(NSData *)data
{
    if (self = [super init]) {
        _data = data;
    }
    return self;
}

- (UIImage *)decodeImage
{
    NSData *data = _data;
    if (!data || data.length == 0) {
        return nil;
    }
    CGFloat scale = MAX(1, [UIScreen mainScreen].scale);
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        NSLog(@"%s  decode error: source is null", __func__);
        return nil;
    }
    
    // 获取图片信息
    CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    NSDictionary *properties = (__bridge NSDictionary *)imageProperties;
    NSNumber *width = properties[(NSString *)kCGImagePropertyPixelWidth];
    NSNumber *height = properties[(NSString *)kCGImagePropertyPixelHeight];
    
    // 设置解码选项
    NSDictionary *options = @{
        (NSString *)kCGImageSourceCreateThumbnailWithTransform: @(YES),
        (NSString *)kCGImageSourceShouldCache: @(YES),
        (NSString *)kCGImageSourceThumbnailMaxPixelSize: @(MAX(width.intValue, height.intValue) * scale)
    };
    
    CGImageRef decompressedImage = CGImageSourceCreateImageAtIndex(source, 0,
                                                                 (__bridge CFDictionaryRef)options);
    
    if (!decompressedImage) {
        if (imageProperties) {
            CFRelease(imageProperties);
        }
        CFRelease(source);
        NSLog(@"%s  decode error: decompressedImage is null", __func__);
        return nil;
    }
    
    // 转换为位图，PNG 需要保留透明通道
    size_t imageWidth = CGImageGetWidth(decompressedImage);
    size_t imageHeight = CGImageGetHeight(decompressedImage);
    size_t scaledWidth = imageWidth * scale;
    size_t scaledHeight = imageHeight * scale;
    size_t bytesPerRow = scaledWidth * 4;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                               scaledWidth,
                                               scaledHeight,
                                               8,
                                               bytesPerRow,
                                               colorSpace,
                                               kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    if (!context) {
        CGImageRelease(decompressedImage);
        CGColorSpaceRelease(colorSpace);
        if (imageProperties) {
            CFRelease(imageProperties);
        }
        CFRelease(source);
        NSLog(@"%s  decode error: context is null", __func__);
        return nil;
    }
    
    CGContextScaleCTM(context, scale, scale);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), decompressedImage);
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(context);
    UIImage *result = [UIImage imageWithCGImage:scaledImage scale:scale orientation:UIImageOrientationUp];
    
    // 清理资源
    CGImageRelease(scaledImage);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(decompressedImage);
    if (imageProperties) {
        CFRelease(imageProperties);
    }
    CFRelease(source);
    result.zy_format = ZYImageFormatPng;
    return result;
}
@end
